<template>
  <div style="width: auto; height: 530px" id="echarts1"></div>
</template>

<script>
import echarts from "echarts";
import { getMonthLine } from "@/api";

const colors = ["#5470C6", "#EE6666"];
export default {
  name: "echarts1",
  data() {
    return {
      option: {
        colors: colors,
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["异常订单", "总下单数"],
        },
        toolbox: {
          show: true,
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        calculable: true,
        xAxis: [
          {
            type: "category",
            // prettier-ignore
            data: [],
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        series: [
          {
            name: "异常订单",
            type: "bar",
            data: [],
            markPoint: {
              data: [
                { type: "max", name: "Max" },
                { type: "min", name: "Min" },
              ],
            },
            markLine: {
              data: [{ type: "average", name: "Avg" }],
            },
          },
          {
            name: "总下单数",
            type: "bar",
            data: [],
            markPoint: {},
            markLine: {
              data: [{ type: "average", name: "Avg" }],
            },
          },
        ],
      },
    };
  },
  mounted() {
    this.echartsInit();
    this.getMonthLine();
  },
  methods: {
    echartsInit() {
      // 在生命周期中挂载
      echarts.init(document.getElementById("echarts1")).setOption(this.option);
    },
    async getMonthLine() {
      let res = await getMonthLine();
      if (res.data.status === 200) {
        let date = [];
        let count = [];
        let error = [];
        res.data.data.forEach((item) => {
          date.push(item.dateTime);
          count.push(item.count);
          error.push(item.Error);
        });
        this.option.xAxis[0].data = date;
        this.option.series[0].data = error;
        this.option.series[1].data = count;
      }
    },
  },
  //数据自动刷新，必然需要一个监听机制告诉Echarts重新设置数据
  watch: {
    //观察option的变化
    option: {
      handler(newVal, oldVal) {
        console.log(newVal);
        if (newVal) {
          this.echartsInit();
        }
      },
      deep: true, //对象内部属性的监听，关键。
    },
  },
};
</script>

<style scoped></style>
